<template>
  <div class="seckill-detail-page">
    <el-main class="main-content">
      <h2 class="page-title">{{ activity.name }} - 秒杀活动详情</h2>
      
      <!-- Activity Info -->
      <el-card class="activity-info-card" shadow="hover">
        <div class="activity-info">
          <h3 class="activity-title">{{ activity.name }}</h3>
          <p class="info-item">活动时间: {{ formatDate(activity.startTime) }} - {{ formatDate(activity.endTime) }}</p>
          <p class="info-item">状态: {{ getActivityStatus(activity.status) }}</p>
        </div>
      </el-card>

      <!-- Seckill Items -->
      <h3 class="section-title">秒杀商品</h3>
      <el-row :gutter="20" class="seckill-items-grid">
        <el-col :span="6" v-for="item in seckillItems" :key="item.skuId" class="seckill-item-card">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div class="item-content">
              <img :src="item.productImage || item.spuMainImage" class="item-image" alt="商品图片" />
              <div class="item-info">
                <h4 class="item-title">{{ item.skuName }}</h4>
                <p class="item-seckill-price">秒杀价: ¥{{ item.seckillPrice }}</p>
                <p class="item-stock">库存: {{ item.seckillStock }}</p>
                <p class="item-limit">限购: {{ item.limitPerUser }}件/人</p>
                <div class="action-row">
                  <div class="quantity-selector">
                    <span class="quantity-label">选择数量:</span>
                    <el-input-number
                      v-model="item.quantity"
                      :min="1"
                      :max="Math.min(item.limitPerUser, item.seckillStock)"
                      size="small"
                      :disabled="item.seckillStock <= 0 || isSubmitting[item.skuId]"
                      @change="handleQuantityChange(item)"
                      class="quantity-input"
                    />
                  </div>
                  <el-button
                    type="danger"
                    size="small"
                    :disabled="item.seckillStock <= 0 || item.quantity <= 0 || isSubmitting[item.skuId]"
                    :loading="isSubmitting[item.skuId]"
                    @click="placeOrder(item)"
                    class="seckill-button"
                  >立即秒杀</el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- Pagination for Seckill Items -->
      <div class="pagination" v-if="itemTotal > 0">
        <el-pagination
          v-model:current-page="itemCurrentPage"
          v-model:page-size="itemPageSize"
          :total="itemTotal"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleItemPageSizeChange"
          @current-change="handleItemPageChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getSeckillActivity, getSeckillItems, placeSeckillOrder } from '@/api/promotion';
import { useUserInfoStore } from '@/stores/userInfo'

const userInfoStore = useUserInfoStore();
const route = useRoute();
const router = useRouter();
const activityId = ref(route.params.promotionId);
const activity = ref({});
const seckillItems = ref([]);
const itemCurrentPage = ref(1);
const itemPageSize = ref(10);
const itemTotal = ref(0);
const isSubmitting = ref({});

// Methods
const fetchActivity = async () => {
  try {
    const response = await getSeckillActivity(activityId.value);
    console.log(response)
    if (response.data.code === "0" || response.data.code === "200") {
      activity.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取秒杀活动失败');
    }
  } catch (error) {
    ElMessage.error('获取秒杀活动失败');
  }
};

const fetchSeckillItems = async (page = 1, size = 10) => {
  try {
    const response = await getSeckillItems(activityId.value, page, size);
    console.log(response)
    if (response.data.code === "0" || response.data.code === "200") {
      seckillItems.value = response.data.data.records.map(item => ({
        ...item,
        quantity: 1 // 默认数量为1
      }));
      itemTotal.value = response.data.data.records.length;
      itemCurrentPage.value = page;
      itemPageSize.value = size;
      // 初始化提交状态
      seckillItems.value.forEach(item => {
        isSubmitting.value[item.skuId] = false;
      });
    } else {
      ElMessage.error(response.data.message || '获取秒杀商品失败');
    }
  } catch (error) {
    ElMessage.error('获取秒杀商品失败');
  }
};

const placeOrder = async (item) => {
  if (item.quantity <= 0 || item.quantity > item.limitPerUser || item.quantity > item.seckillStock) {
    ElMessage.error('无效的购买数量');
    return;
  }
  try {
    isSubmitting.value[item.skuId] = true;
    const userId = userInfoStore.userInfo.id;
    const response = await placeSeckillOrder(userId, activityId.value, item.skuId, item.quantity);
    if (response.data.code === "0" || response.data.code === "200") {
      ElMessage.success(response.data.message);
      await fetchSeckillItems(itemCurrentPage.value, itemPageSize.value);
      console.log(response)
      const orderSn = response.data.data.orderSn;

      router.push({ path: '/pay/choose', query: { orderSn } });
    } else {
      ElMessage.error(response.data.message || '下单失败');
    }
  } catch (error) {
    ElMessage.error('下单失败');
  } finally {
    isSubmitting.value[item.skuId] = false;
  }
};

const handleQuantityChange = (item) => {
  if (item.quantity < 1) {
    item.quantity = 1;
    ElMessage.warning('购买数量不能少于1');
  } else if (item.quantity > item.limitPerUser) {
    item.quantity = item.limitPerUser;
    ElMessage.warning(`购买数量不能超过${item.limitPerUser}件`);
  } else if (item.quantity > item.seckillStock) {
    item.quantity = item.seckillStock;
    ElMessage.warning('购买数量不能超过剩余库存');
  }
};

const handleItemPageChange = async () => {
  await fetchSeckillItems(itemCurrentPage.value, itemPageSize.value);
};

const handleItemPageSizeChange = async () => {
  itemCurrentPage.value = 1; // Reset to first page
  await fetchSeckillItems(1, itemPageSize.value);
};

const getActivityStatus = (status) => {
  const statuses = { 0: '停用', 1: '启用' };
  return statuses[status] || '未知';
};

const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString() : 'N/A';
};

// const parseScope = (scopeJson) => {
//   try {
//     return JSON.stringify(scopeJson, null, 2);
//   } catch {
//     return '无法解析';
//   }
// };

// const parseConfig = (configJson) => {
//   try {
//     return JSON.stringify(configJson, null, 2);
//   } catch {
//     return '无法解析';
//   }
// };

// Lifecycle
onMounted(async () => {
  await Promise.all([
    fetchActivity(),
    fetchSeckillItems(),
  ]);
});
</script>

<style scoped>
.seckill-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
  text-align: center;
}

.main-content {
  margin: 24px 0;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 48px);
}

.activity-info-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.activity-info {
  padding: 16px;
}

.activity-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.info-item {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 24px 0 16px;
}

.seckill-items-grid {
  margin-bottom: 24px;
}

.seckill-item-card .el-card {
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.seckill-item-card .el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.15);
}

.item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.item-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  margin-bottom: 12px;
}

.item-info {
  text-align: center;
  width: 100%;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.item-price, .item-seckill-price, .item-stock, .item-limit {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.item-seckill-price {
  color: #f56c6c;
  font-weight: 500;
}

.action-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-label {
  font-size: 14px;
  color: #606266;
}

.quantity-input {
  width: 100px;
}

.seckill-button {
  flex: 1;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
</style>